package com.luhuiguo.cms.server.handler;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Component;

import com.luhuiguo.cms.server.entity.Article;
import com.luhuiguo.cms.server.service.ArticleService;
import com.luhuiguo.cms.server.service.MapperService;
import com.luhuiguo.cms.shared.model.ArticleModel;
import com.luhuiguo.cms.shared.rpc.FetchArticles;
import com.luhuiguo.cms.shared.rpc.FetchArticlesResult;
import com.luhuiguo.gwt.dispatcher.server.ActionHandler;
import com.luhuiguo.gwt.dispatcher.server.ExecutionContext;
import com.luhuiguo.gwt.dispatcher.shared.exception.ActionException;

@Component
public class FetchArticlesHandler implements ActionHandler<FetchArticles, FetchArticlesResult> {

    @Autowired
    private MapperService mapperService;

    @Autowired
    private ArticleService articleService;

    @Override
    @PreAuthorize("isAuthenticated()")
    public FetchArticlesResult execute(FetchArticles action, ExecutionContext context) throws ActionException {

        List<Article> list = articleService.findArticlesByChannel(action.getChannel(), action.getStart(), action
                .getOffset());
        int count = articleService.getCountByChannel(action.getChannel());

        return new FetchArticlesResult(mapperService.mapList(list, ArticleModel.class), action.getStart(), action
                .getOffset(), count);
    }

    @Override
    public Class<FetchArticles> getActionType() {
        return FetchArticles.class;
    }

    @Override
    public void rollback(FetchArticles action, FetchArticlesResult result, ExecutionContext context)
            throws ActionException {

    }

}
